// ws_party_const/components/organ-construction.js
const { $util } = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShow: {
      type: Boolean,
      value: false,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    scrollId: `id0`,
    id: 0,
    directory: [],
    searchVal: '',
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getList() {
      let { id } = this.data;
      $util.request({
        url: 'entry/wxapp/partyman.organ.getorganlist',
        data: { id: id },
        showLoading: true,
        success: (res) => {
          this.setData({
            organs: res.organs,
          });
        },
      });
    },
    // 获取子文件列表
    getChildList(e) {
      const {
        id,
        idx,
        title,
      } = e.currentTarget.dataset;
      let {
        directory,
        id: did,
      } = this.data;
      if (id === did) return;
      if (idx !== undefined) {
        directory.splice(idx, directory.length - idx);
      }
      this.setData({
        id: id,
        title: title,
        page: 1,
        directory,
      }, () => {
        this.getDirectory();
        this.getList();
      });
    },
      // 获取文件目录
    getDirectory() {
      let directory = this.data.directory;
      let item = [{
        id: this.data.id,
        title: this.data.title,
      }];
      directory = [...directory, ...item];
      this.setData({
        directory, 
        scrollId: `id${this.data.id}`,
      });
    },
    getSureOrg() {
      this.setData({
        isShow: false,
      });
      if (this.data.directory.length > 0) {
        this.triggerEvent('getOrgan', {
          id: this.data.directory[this.data.directory.length - 1].id,
          name: this.data.directory[this.data.directory.length - 1].title,
        })
      }
    },
    getShowOrg() {
      this.setData({
        isShow: !this.data.isShow,
      });
      this.clearSearchVal();
    },
    onSearch() {
      let { searchVal } = this.data;
      if (searchVal == '') {
        return wx.showToast({
          title: '请输入组织名称',
          icon: 'none',
          duration: 1500,
        });
      }
      $util.request({
        url: 'entry/wxapp/partyman.organ.getlistbyname',
        data: { name: searchVal },
        showLoading: true,
        success: (res) => {
          if (res.errno === 0) {
            this.setData({
              directory: [],
              organs: res.organs,
            });
          }
        },
      });
    },
    setSearchVal(e) {
      this.setData({
        searchVal: e.detail.value,
      });
    },
    // 重置数据
    clearSearchVal() { 
      this.setData({
        id: 0,
        searchVal: '',
        directory: [],
      });
      this.getList();
    }
  },

  ready () {
    this.getList();
    this.getDirectory();
  }
})
